<template>
  <h3>{{title}}</h3>
  <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="addType">新增</el-button>
  <el-button type="warning" icon="el-icon-edit" size="mini" @click="editType">修改</el-button>
  <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteType">删除</el-button>
  <ul class="an-type-list">
    <li
      v-for="item in list"
      :key="item.id"
      @click="changeActive(item)"
      :class="activeId==item.id?'active':''"
    >{{item.typeName}}</li>
  </ul>

  <goods-type-add
    v-if="isVisible"
    v-model:isVisible="isVisible"
    :parentID="tageParentID"
    :typeDate="tageDate"
  />
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { GoodsType } from "@/utils/interface";
import goodsTypeAdd from "../goodsTypeAdd/index.vue";
@Options({
  components: {
    goodsTypeAdd,
  },
  props: {
    title: {
      type: String,
      default: "二级分类",
    },
    list: {
      type: Array,
      default: (): Array<GoodsType> => [],
    },
    parentID: {
      // 父级分类ID
      type: Number,
      default: null,
    },
  },
  watch: {
    list: {
      handler() {
        this.init();
      },
      immediate: true,
    },
  },
  emits: ["callBack"],
})
export default class typeList extends Vue {
  [x: string]: any;
  activeId: Number = 0; // 选中的ID
  tageParentID: Number = 0; // 需要编辑的分类的父级ID
  tageDate = {}; // 需要编辑的分类数据
  isVisible: Boolean = false;

  init() {
    if (this.list.length > 0) {
      this.changeActive(this.list[0]);
    }
  }

  // 切换选中
  changeActive(item: GoodsType) {
    this.activeId = item.id;
    this.$emit("callBack", item);
  }

  // 新增
  addType() {
    if (!this.isMainType) {
      this.tageParentID = this.parentID;
    }
    this.tageDate = {};
    this.isVisible = true;
  }

  // 修改
  editType() {
    let tag = {};
    this.list.forEach((element: GoodsType) => {
      if (element.id == this.activeId) {
        tag = element;
      }
    });
    this.tageDate = tag;
    this.isVisible = true;
  }

  // 删除
  deleteType() {
    if (this.activeId) {
      this.API.goodsTypeDelete(this.activeId).then(() => {
        this.$message.success("操作成功");
        // 更新分类数据
        this.$store.dispatch("appModule/updateType");
      });
    }
  }
}
</script>

<style lang="scss">
.an-type-list {
  padding: 15px 0;
  li {
    padding: 8px;
    cursor: pointer;
    &.active {
      background-color: #f9efc4;
    }
  }
}
</style>